﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Marbles.Core.Connectors;

namespace Marbles.Core.Controls
{
    public class ForumDiscussionList : WebControl
    {

        public Int32 DiscussionCount { get { object obj = ViewState["DiscussionCount"]; return (obj == null) ? 10 : Convert.ToInt32(obj); } set { ViewState["DiscussionCount"] = value; } }
        public string Title { get { object obj = ViewState["Title"]; return (obj == null) ? "Latest {0} discussions" : obj.ToString(); } set { ViewState["Title"] = value; } }

        public ForumDiscussionList()
            : base(HtmlTextWriterTag.Div)
        {
        }

        protected override void CreateChildControls()
        {
            Core.Content.Sites.SiteDefinition site = Core.Content.Sites.SiteDefinition.GetCurrent();
            DataConnection dbc = new DataConnection();
            Command cmd = new Command(string.Format("SELECT TOP {0} postid, forumname, title, postdate, postby FROM forumitems WHERE approved = 1 AND sticky = 0 AND siteid = @siteid ORDER BY postdate DESC", DiscussionCount));
            cmd.AddParameter("@siteid", site.SiteId);
            DataTable dt = dbc.FetchDataTable(cmd);
            base.CreateChildControls();

            Table tbl = new Table();
            tbl.Width = new Unit(100, UnitType.Percentage);
            tbl.ID = this.ClientID + "_List";
            this.Controls.Add(tbl);
            TableHeaderRow headerRow = new TableHeaderRow();
            TableHeaderCell headerCell = new TableHeaderCell();
            headerCell.Wrap = false;
            headerRow.CssClass = "header";
            headerCell.Text = "<center>" + string.Format(this.Title, DiscussionCount) + "</center>";
            headerRow.Cells.Add(headerCell);
            tbl.Rows.Add(headerRow);

            foreach (DataRow dr in dt.Rows)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                row.CssClass = "item";
                cell.Text = string.Format("<div style=\"text-align:left;width:100%;overflow:hidden;white-space:nowrap;\"  title=\"{2} on {3} \"><a href=\"/BBS/Discussion.aspx?f={0}&t={1}\">{2}</a></div>", dr["forumname"], dr["postid"], dr["title"],dr["postdate"]);
                row.Cells.Add(cell);
                tbl.Rows.Add(row);
            }

            TableFooterRow footerRow = new TableFooterRow();
            footerRow.CssClass = "footer";
            TableCell footerCell = new TableCell();
            footerRow.Cells.Add(footerCell);
            footerCell.Text = "<center><a href=\"/BBS/\" title=\"View Discussion Forums\" >View Forums</a></center>";
            tbl.Rows.Add(footerRow);
        }
    }
}
